<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="井盖编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入井盖编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:cover:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:cover:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:cover:import']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:cover:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:cover:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="coverList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="id" width="55" align="id" type="index" />
      <el-table-column label="井盖编号" align="center" prop="code" />
      <el-table-column label="井盖用途" align="center" prop="coverUsefor">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.well_lid_use"
            :value="scope.row.coverUsefor"
          />
        </template>
      </el-table-column>
      <el-table-column label="井盖类型" align="center" prop="coverType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.well_lid_type"
            :value="scope.row.coverType"
          />
        </template>
      </el-table-column>
      <el-table-column label="所属区域" align="center" prop="region" />
      <el-table-column label="权属单位" align="center" prop="flats">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.ownership_unit"
            :value="scope.row.flats"
          />
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:cover:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:cover:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="excelRules" label-width="110px">
        <el-form-item label="行政区" :required="true" prop="region">
          <el-cascader
            size="large"
            :options="options"
            v-model="form.region"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="井盖权属单位" :required="true" prop="flats">
          <el-select v-model="form.flats">
            <el-option
              v-for="dict in dict.type.ownership_unit"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-change="excelChange"
          :auto-upload="false"
          drag
          :file-list="fileList"
          name="file"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <span>提示：仅允许导入“xls”、“xlsx”格式文件！</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
    </el-dialog>
    <!-- 新增井盖管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="井盖编号" prop="code"  class="tests">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item label="所属区域" :required="true" prop="region">
          <el-cascader
            size="large"
            :options="options"
            v-model="form.region"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="井盖权属单位" :required="true" prop="flats">
          <el-select v-model="form.flats">
            <el-option
              v-for="dict in dict.type.ownership_unit"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="详细地址" :required="true" prop="address" class="tests">
          <el-input v-model="form.address" />
        </el-form-item>

        <el-form-item label="坐标位置"  prop="latAndlng">
          <el-input v-model="form.latAndlng"  @focus="selectLatAndLng()" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="井盖类型" :required="true" prop="coverType">
          <el-select v-model="form.coverType">
            <el-option
              v-for="dict in dict.type.well_lid_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="井盖用途" :required="true" prop="coverUsefor">
          <el-select v-model="form.coverUsefor">
            <el-option
              v-for="dict in dict.type.well_lid_use"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="地图选点" :visible.sync="dialogTableVisible" center :append-to-body='true' :lock-scroll="false"  width="50%">
      <my-component @latAndLngValue="pointValue"></my-component>
      <el-button type="primary" @click="dialogTableVisible = false">确 定</el-button>
      <el-button @click="dialogTableVisible = false">取 消</el-button>
    </el-dialog>

    <!-- 修改井盖管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="XGopen"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="110px">
        <el-form-item label="井盖编号" :required="true" prop="code" class="tests">
          <el-input v-model="form.code" disabled="disabled" />
        </el-form-item>
        <el-form-item label="井盖权属单位" :required="true" prop="flats">
          <el-select v-model="form.flats" disabled="disabled">
            <el-option
              v-for="dict in dict.type.ownership_unit"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="详细地址" :required="true" prop="address" class="tests">
          <el-input v-model="form.address" class="res"/>
        </el-form-item>

        <el-form-item label="坐标位置"  prop="latAndlng">
          <el-input v-model="form.latAndlng"  @focus="selectLatAndLng()" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="井盖类型" :required="true" prop="coverType">
          <el-select v-model="form.coverType">
            <el-option
              v-for="dict in dict.type.well_lid_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="井盖用途" :required="true" prop="coverUsefor">
          <el-select v-model="form.coverUsefor">
            <el-option
              v-for="dict in dict.type.well_lid_use"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="Xcancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCover,
  getCover,
  delCover,
  addCover,
  updateCover,
  downTemplate,
  addCoverExcel,
} from "@/api/system/cover";
import { pcaTextArr } from "element-china-area-data";
import { mapData } from "../../../api/address";
import MyComponent from '../../components/MyComponent.vue'
//记得导入 getToken
import { getToken } from "@/utils/auth";
export default {
  components:{
    'my-component': MyComponent
  },
  name: "Cover",
  dicts: ["well_lid_type", "well_lid_use", "ownership_unit"],
  data() {
    return {
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/system/cover/importData",

      },
      fileList: [],
      files: "",
      file:"",
      options: pcaTextArr,
      dialogTableVisible: false,
      // options: mapData,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 井盖管理表格数据
      coverList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      XGopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        region: null,
        flats: null,
        address: null,
        coverType: null,
        coverUsefor: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "井盖编号不能为空", trigger: "blur" },
        ],
        region: [
          { required: true, message: "所属区域不能为空", trigger: "change" },
        ],
        flats: [
          { required: true, message: "井盖权属单位不能为空", trigger: "blur" },
        ],
        address: [
          { required: true, message: "详细地址不能为空", trigger: "blur" },
        ],
        coverType: [
          { required: true, message: "井盖类型不能为空", trigger: "blur" },
        ],
        coverUsefor: [
          { required: true, message: "井盖用途不能为空", trigger: "blur" },
        ],
        latAndlng:[
          { required: true, message: "坐标位置不能为空", trigger: "blur" },
        ]
      },
      excelRules:{
        region: [
          { required: true, message: "所属区域不能为空", trigger: "blur" },
        ],
        flats: [
          { required: true, message: "井盖权属单位不能为空", trigger: "blur" },
        ],
      }

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "井盖导入"; // todo
      this.form = {
        region: null,
        flats: null
      };
      this.resetForm("form");
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/cover/downInChargeOfTemplate",
        {},
        `cover_template_${new Date().getTime()}.xls`
      ); // todo
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      console.log("file"+file);
      this.upload.isUploading = true;
      this.file = file;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      // this.$refs.upload.submit();
      let formData = new FormData();
      console.log(this.form.region)
      // formData.append("file",this.file);  //追加文件到请求接口
      formData.append("region", this.form.region);  //追加文件名称到请求接口
      formData.append("flats", this.form.flats); //追加文件类型到请求接口
      formData.append('file', this.file.raw)
      formData.forEach((key, val) => {
        console.log("key %s: value %s:", key, val);
      })
      this.$refs["form"].validate((valid) => {
        if (valid) {
          addCoverExcel(formData).then((response) => {
           this.upload.open=false;
            this.getList();
            console.log("1");
          });
        }
      });
    },
    excelChange(file, fileList) {
      if (/.(txt)$/.test(file.name)) {
        this.$message({
          message: "不允许上传以txt结尾的文件",
          type: "warning"
        });
        this.$refs.uploadProduct.clearFiles();
        return
      }
      this.upload.isUploading = true;
      this.file = file;

    },
    handleChange(value) {
      this.form.region = value;

    },
    /** 查询井盖管理列表 */
    getList() {
      this.loading = true;
      listCover(this.queryParams).then((response) => {
        this.coverList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //取消按钮 （修改）
    Xcancel() {
      this.XGopen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        region: null,
        flats: null,
        address: null,
        coverType: null,
        coverUsefor: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加井盖";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
        getCover(id).then((response) => {
        this.form = response.data;
        this.form.latAndlng = response.data.lat + "," + response.data.lng;
        // this.form.region = response.data.region.split("/");
        this.XGopen = true;
        this.title = "修改井盖";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // alert(this.form.region);
          this.form.region = Array.isArray(this.form.region)?this.form.region.join("/"):this.form.region;
          if (this.form.id != null) {
            updateCover(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.XGopen = false;
              this.getList();
            });
          } else {
            addCover(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch((err) =>{
              this.form.region = this.form.region.split("/");
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除选中项?")
        .then(function () {
          return delCover(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/cover/export",
        {
          ...this.queryParams,
        },
        `cover_${new Date().getTime()}.xlsx`
      );
    },
    selectLatAndLng(){
      this.dialogTableVisible = true
    },
    pointValue(value){
      this.form.lat = value.lat
      this.form.lng = value.lng
      this.form.latAndlng = value.lat + ',' + value.lng
    },

  }
};
</script>
<style>
.tests{
  width: 330px;
}
</style>
